<?php
class Admin_LoginController extends Zend_Controller_Action
{	
    public function init() {
         
    }
    public function indexAction()
    {
    	$this->view->title="Login";	
        $this->_helper->layout->setLayout('login');
    	$regMsg                = new Zend_Session_Namespace ( 'msg' );
    	if($this->_request->isPost()){
            $username          = $this->_request->getParam('username', false);
            $password          = $this->_request->getParam('password', false);
            
           
    			if ($username == NULL ) {
					$regMsg->msg = "Username empty!";
                    $this->_helper->getHelper ( 'Redirector' )->gotoUrl ( "/admin/login" );
				}
    			elseif($password == NULL ) {
					$regMsg->msg = "Password empty!";
                    $this->_helper->getHelper ( 'Redirector' )->gotoUrl ( "/admin/login" );
				}
    			
		  	    $db = Zend_Db_Table::getDefaultAdapter ();
				//create the auth adapter
			    $authAdapter = new Zend_Auth_Adapter_DbTable($db);
                $authAdapter->setTableName('users')
                        ->setIdentityColumn('username')
                        ->setCredentialColumn('password');
                        
        
			
                //5. Dua vao so sanh voi du lieu khai bao o muc 3
                $authAdapter->setIdentity($username);
                $authAdapter->setCredential(md5($password));
    				
				//authenticate
                    $result = $authAdapter->authenticate();
                   
	    			if ($result->isValid ()) {

						$auth = Zend_Auth::getInstance ();
						$auth->setStorage ( new Zend_Auth_Storage_Session ( 'admin' ) );
						$storage = $auth->getStorage ();	
					
						$storage->write ( $authAdapter->getResultRowObject ( array ('id') ) );
						//login success
						$this->_helper->getHelper ( 'Redirector' )->gotoUrl ( "/admin" );
					} else {
						$regMsg->msg = "The username or password you entered is incorrect";
					}
				
	
    	}
    	$this->view->response = $regMsg->msg;
		$regMsg->unsetAll ();	
    }
    
	public function logoutAction() {
        Zend_Auth::getInstance ()->setStorage ( new Zend_Auth_Storage_Session ( 'admin' ) )->clearIdentity ();
	
		$this->_helper->getHelper ( 'Redirector' )->gotoUrl ( "/admin/login" );
	}		
}
